package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 韩
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${community.path.upload}")
    private String upload;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;

    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model) {
        // 浏览器上传七牛云需要在服务端获取的信息
        // 上传文件名称
        String fileName = CommunityUtil.generateUUID();
        // 设置响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJsonString(0));
        // 生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

        System.out.println("jhjjj");
        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);
        return "/site/setting";
    }

    // 更新头像路径
    //七牛云响应数据表示成功后异步请求更新user表中的头像url
    @RequestMapping(path = "/upload/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJsonString(1, "文件名不能为空!");
        }

        //更新数据库中的头像url
        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeaderUrl(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJsonString(0);
    }

    //弃用
    //上传用户头像到本地
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您没有选择图片！");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        //获取上传图片的后缀，因为后缀格式不能改变
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "您上传的图片格式错误！");
            return "/site/setting";
        }

        //生成随机文件名，避免造成重复文件名
        filename = CommunityUtil.generateUUID() + "." + suffix;
        //创建要存放的文件路径
        File destFile = new File(upload + "/" + filename);
        try {
            //存储文件
            headerImage.transferTo(destFile);
        } catch (IOException e) {
            logger.error("文件上传失败：" + e.getMessage());
            throw new RuntimeException("文件上传失败", e);
        }

        //更新当前用户的头像路径
        // http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeaderUrl(user.getId(), headerUrl);
        return "redirect:/index";
    }

    //弃用
    //在本地获取用户的头像
    @RequestMapping(path = "/header/{filename}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response) {
        //获取图片在服务器的存储路径
        filename = upload + "/" + filename;
        String suffix = filename.substring(filename.lastIndexOf("."));

        //响应图片
        response.setContentType("image/" + suffix);
        try {
            ServletOutputStream os = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(filename);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("文件上传失败：" + e.getMessage());
        }
    }

    @RequestMapping(path = "/alter/password", method = RequestMethod.POST)
    public String alterPassword(String originalPassword, String newPassword, HttpServletRequest request, Model model) {
        if (StringUtils.isBlank(originalPassword) || StringUtils.isBlank(newPassword)) {
            model.addAttribute("passwordMsg", "密码不能为空！");
            return "/site/setting";
        }
        //验证原来的密码是否正确
        User user = hostHolder.getUser();
        if (!user.getPassword().equals(CommunityUtil.md5(originalPassword + user.getSalt()))) {
            System.out.println("mimacuowu");
            model.addAttribute("passwordMsg", "原密码不正确，请重新输入！");
            return "/site/setting";
        }
        //更新密码
        userService.updatePassword(user, newPassword);

        //退出登录
        String ticket = CookieUtil.getValue(request, "ticket");
        userService.logout(ticket);
        return "redirect:/login";
    }


    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        model.addAttribute("user", user);
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        //关注的用户数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        //实体的粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        //登录用户对该用户的关注状态
        boolean followStatus = false;
        if (hostHolder.getUser() != null) {
            followStatus = followService.hasFollow(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("followStatus", followStatus);
        return "/site/profile";
    }
}
